# _*_ coding: utf-8 _*_
# @Author   : Wei Yue
# @Time     : 2024-09-04 16:25
# @Function :

import re
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

from common.constant import PROJECT_DIR, CarTopics


class Article:
    def __init__(self, source, title, url, date, topic: CarTopics, keyword=None):
        self.source = source
        self.title = title
        self.url = url
        self.date = date
        self.article_detail = None
        self.topic = topic
        self.keyword = keyword

    def __str__(self):
        return f"{self.topic.value}-{self.source}-{self.title} - {self.url} - {self.date} \n {self.article_detail}"

    def __eq__(self, other):
        if not isinstance(other, Article):
            return NotImplemented
        return self.title == other.title

    def __hash__(self):
        return hash(self.title)


class ArticleDetail:
    def __init__(self, content, image_urls):
        self.content = content
        self.image_urls = image_urls

    def __str__(self):
        return f"{self.content} \n {self.image_urls}"


class Crawler:

    def __init__(self, url):
        # conf = configparser.ConfigParser()
        # conf.read('./config.txt', encoding='utf-8')
        self.url = url
        self.chrome_options = Options()
        self.chrome_options.add_argument("--headless")
        # self.chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")  # 前面设置的端口号
        # 你可以通过手工先实现一些自动化难处理的操作，让 selenium 绕过这些复杂操作，然后再执行自动化。
        # self.threadOs = Thread(target=lambda: os.system(
        #     'chrome.exe --headless --remote-debugging-port=9222 --user-data-dir="E:\data_info\selenium_data'))
        # self.threadOs.daemon = True
        # self.threadOs.start()
        self.browser = webdriver.Chrome(service=Service(PROJECT_DIR + '/resource/chromedriver.exe'),
                                        options=self.chrome_options)  # executable执行webdriver驱动的文件
        self.browser.implicitly_wait(5)
        self.openPage(self.url)

    def openPage(self, url):
        self.browser.get(url)

    def release(self):
        self.browser.quit()

    def closeWindowKeepFirst(self):
        # 获取当前所有窗口的句柄
        current_window_handles = self.browser.window_handles
        # 保存第一个窗口的句柄
        first_window_handle = current_window_handles[0]
        # 遍历所有窗口句柄并关闭它们，除了第一个窗口
        for handle in current_window_handles:
            if handle != first_window_handle:
                self.browser.switch_to.window(handle)
                self.browser.close()
        # 最后切换回第一个窗口
        self.browser.switch_to.window(first_window_handle)

    def switchToNewWindow(self):
        new_window_handle = \
            [handle for handle in self.browser.window_handles if
             handle != self.browser.current_window_handle][0]
        self.browser.switch_to.window(new_window_handle)

    def getPageNumber(self):
        return len(self.browser.window_handles)

    def handle_content(self, content_list):
        content_before = "".join(content_list)
        reg = re.compile(r'<[^>]+>', re.S)
        content = reg.sub('', content_before)
        return content


if __name__ == '__main__':
    dongchedi = Crawler('https://www.dongchedi.com/')
    dongchedi.openPage(dongchedi.url)
    dongchedi.release()  # 确保浏览器关闭
